﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;

namespace WebMainSite
{
    public class BasePage : System.Web.UI.Page
    {
        public BasePage()
        {
            this.Load += new EventHandler(BasePage_Load);
        }

        private void BasePage_Load(object sender, EventArgs e)
        {
            if (Session["userInfo"] == null)
            {
                //若不是通过Login.aspx页面登录的话，不会有如下两个参数，就跳转到登陆页面
                string[] allKeys = Request.Form.AllKeys;
                if (((IList)allKeys).Contains("username") && ((IList)allKeys).Contains("password"))
                {
                    string userName = Request.Form["username"].Trim();
                    string passWord = Request.Form["password"].Trim();
                    SetSession(userName, MD5Encryption(passWord));
                }
                else
                {
                    Response.Redirect("login.aspx");
                }
            }
        }
        /// <summary>
        /// 通过登录页面送过来的用户名和密码查询数据里面是否有该用户，有的话把他的个人信息放在Session里面
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        private void SetSession(string userName, string passWord)
        {
            string strWhere = "UserID='" + userName + "' and PassWord='" + passWord + "'";
            MySite.BLL.UserInfo userInfoBll = new MySite.BLL.UserInfo();
            DataSet ds = userInfoBll.GetList(strWhere);
            if (ds.Tables[0] != null && ds.Tables[0].Rows.Count == 1)
            {
                MySite.Model.UserInfo userInfo = new MySite.Model.UserInfo();
                userInfo.PassWord = ds.Tables[0].Rows[0]["PassWord"].ToString();
                userInfo.UserID = ds.Tables[0].Rows[0]["UserID"].ToString();
                userInfo.UserName = ds.Tables[0].Rows[0]["UserName"].ToString();
                Session["userInfo"] = userInfo;
            }
            else
            {
                //这个就此中断，直接跳转，不会再执行继承该基类的其他类的构造函数
                Response.Redirect("login.aspx");
            }
        }
        /// <summary>
        /// MD进行加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string MD5Encryption(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }
    }
}